<template>
	<view class="content">
		<!-- <view class="start-live" @click="startLive"><i class="iconlessonfont icon-shipin"></i></view> -->
		<view class="top">
			<!-- 非直播的未开始课程 -->
			<view class="live-box" v-if="outlineList[index].begin == 2 && outlineList[index].course_service_type != 1">
				<view class="live-box-warp"></view>
				<view class="live-summary">
					<view><text class="live-tip">课程未开始</text></view>
				</view>
			</view>
			<!-- 直播的结束课程 -->
			<view class="live-box" v-if="outlineList[index].begin == 3">
				<view class="live-box-warp"></view>
				<view class="live-summary">
					<view><text class="live-tip">课程已结束</text></view>
				</view>
			</view>
			<!-- 有回放类型课程 -->
			<video :src="outlineList[index].src" controls v-if="outlineList[index].begin == 0"></video>
			<!-- 直播中类型课程||未开始直播类型课程 -->
			<view
				class="live-box"
				id="live"
				v-if="outlineList[index].begin == 1 || (outlineList[index].begin == 2 && outlineList[index].course_service_type == 1)"
				style="background-image: url(../../static/lesson_temp/coverTeacher.jpg);"
			>
				<view class="live-box-warp"></view>
				<!-- 未开始 -->
				<view class="live-summary" v-if="outlineList[index].begin == 2">
					<view><text class="live-tip">直播倒计时</text></view>
					<view>
						<v-time-count :finish="handleTimeCount" :timestamp="outlineList[index].start_time * 1000"></v-time-count>
						<!-- <text class="live-time-count" live_remain>{{ live_remain }}</text> -->
					</view>
				</view>
				<!-- 直播已经开始 -->
				<view class="live-summary" v-else>
					<view class="live-btn-bar">
						<view class="live-btn" @click="startLive"><text>进入直播</text></view>
					</view>
				</view>
			</view>
			<web-view src="/hybrid/html/screen.html" @message="webMessage" webview-styles="live-box" v-if="false"></web-view>
			<view v-if="outlineList[index].begin == 1 && is_live_start" class="video-opration-bar">
				<!-- 直播显示全屏按钮 -->
				<text @click="fullScreen()">全屏</text>
			</view>
			<view class="info">
				<view class="info-left">
					<view class="list-item-index">
						第{{ index + 1 }}课
						<text v-if="outlineList[index].course_service_type != 2">
							丨{{ outlineList[index].start_time | course_time_filter }} {{ outlineList[index].start_time | course_time_filter('HH:mm') }}-{{
								outlineList[index].end_time | course_time_filter('HH:mm')
							}}
						</text>
						丨{{ outlineList[index].course_service_type | course_type_filter }}丨{{ outlineList[index].teacher_name }}
					</view>
					<view class="list-item-name">{{ outlineList[index].detail_title }}</view>
				</view>
				<!-- <view class="info-right">
					<i class="iconfont icondianzan" @click="fullScreen()"></i>
					{{ outlineList[index].like }}
				</view> -->
			</view>
			<view class="title">
				<view class="title-name" :class="titleIndex == index ? 'title-item-active' : ''" v-for="(item, index) in titleList" :key="index" @tap="titleNav(index)">
					{{ item }}
				</view>
			</view>
		</view>
		<view class="list" v-if="titleIndex == 0">
			<view class="list-item" v-for="(item, index) in outlineList" :key="index" @tap="navClick(index, item.id)">
				<view class="list-item-info">
					<view class="list-item-index">
						第{{ index + 1 }}课
						<text v-if="item.course_service_type != 2">
							丨{{ item.start_time | course_time_filter }} {{ item.start_time | course_time_filter('HH:mm') }}-{{ item.end_time | course_time_filter('HH:mm') }}
						</text>
						丨{{ item.course_service_type | course_type_filter }}丨{{ item.teacher_name }}
					</view>
					<view class="list-item-name">{{ item.detail_title }}</view>
				</view>
				<view class="list-item-icon">
					<view v-if="item.begin == 1" class="list-item-begin">正在直播</view>
					<view v-else-if="item.begin == 2">未开始</view>
					<view v-else-if="item.begin == 3">已结束</view>
					<view v-else-if="item.id == saveId" class="list-item-begin">播放中</view>
					<view v-else><i class="iconfont iconshipinziyuan"></i></view>
				</view>
			</view>
		</view>
		<view class="list" v-if="titleIndex == 1">
			<view class="list-item" v-for="(item, index) in dataList" :key="index">
				<view class="list-item-info">
					<view class="list-item-index">
						第{{ index + 1 }}课丨{{ item.type }}丨
						<text v-if="item.files_type == 1">文档</text>
						<text v-if="item.files_type == 2">视频</text>
						<text v-if="item.files_type == 3">音频</text>
					</view>
					<view class="list-item-name">{{ item.name }}</view>
				</view>
				<view class="list-item-icon" v-if="item.files_type != 0" @click="download(item.url)">
					<view v-if="item.files_type == 1"><i class="iconfont iconwendangziyuan"></i></view>
					<view v-if="item.files_type == 2"><i class="iconfont iconshipinziyuan"></i></view>
					<view v-if="item.files_type == 3"><i class="iconfont iconyinpinziyuan"></i></view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import vTimeCount from './components/timecounter'
var wv, wv_w, wv_h; //计划创建的webview
// 注意平台差异
// #ifdef APP-NVUE
const dom = weex.requireModule('#live');
// #endif
// import RTCClient from './components/live-utils/rtc-client.js'
var _this;
export default {
	components:{
		vTimeCount
	},
	data() {
		_this = this;
		return {
			course_id: 1, // 课程 id， 也是作为直播 channelId 传递
			user_id: 3,
			is_live_start: false, // 是否正在直播
			is_fullScreen: false, // 是否全屏，可以点击返回退出全屏
			saveId: 2,
			index: 0,
			outlineList: [],
			titleList: ['课程大纲', '课程资料'],
			titleIndex: 0,
			dataList: [
				//1为文档。2为视频，3为音频
				// { name: '语文中考必备复习方法01', files_type: 1, type: '预习资料' },
				// { name: '语文中考必备复习方法02', files_type: 2, type: '课后练习' },
				// { name: '语文中考必备复习方法03', files_type: 3, type: '课后练习' }
			],
			rtcclient: null,
			rtcConfig: {
				uid: '123',
				host: true,
				dev: 1, // 开发模式
				beauty: true,
				mode: 'live',
				codec: 'h264',
				channel: 'CHANNEL_1',
				key: '00664607af550014c1490e70368bda7318dIAAXzeu2dMO1QuC3lg8JrH8lpgrC3nPsu2CwDc8fzl/T1cecNHLSY0iIEAAGHAAAtvIVXgEAAQBiohRe'
			}
		};
	},
	onLoad(data) {
		// 获取孩子id
		var t_data = uni.getStorageSync('currentChild')
		this.user_id = t_data.student_id;
		_this.outlineList = uni.getStorageSync('outlineList');
		_this.navClick(+data.current_outline || 0);
		_this.dataList = _this.outlineList.map(x => ({
			files_type: x.extend_source_type == '文档' ? 1 : x.extend_source_type == '视频' ? 2 : x.extend_source_type == '音频' ? 3: 0,
			name: x.detail_title,
			type: '课程资料',
			url: x.extend_source_url
		}));
	},
	onReady() {
		// #ifdef APP-PLUS-NVUE || APP-PLUS
		const result = dom.getComponentRect(this.$refs.box, option => {
			console.log('getComponentRect:', option);
			this.size = option.size;
		});
		// #endif
	},
	onShow() {
		if (this.outlineList[this.index].begin === 0) {
			uni.setNavigationBarTitle({
				title: '课程回放'
			});
		} else {
			uni.setNavigationBarTitle({
				title: '我的教室'
			});
			setTimeout(a => {
				uni.createSelectorQuery()
					.select('#live')
					.boundingClientRect(data => {
						// this.size = data
						this.$nextTick(e => {
							console.log('get Rect done ==> ', data);
							(wv_h = data.height), (wv_w = data.width);
						});
					})
					.exec();
			}, 100);
		}
	},
	onPullDownRefresh() {
		this.reload(this.index)
	},
	onBackPress() {
		// 关闭 webview
		// #ifdef APP-PLUS
		if (_this.is_fullScreen) {
			console.log("is full screen")
			// 获取设备屏幕大小信息
			uni.getSystemInfo({
				success(res) {
					console.log(' _ get System Info success := ', res);
					wv.setStyle({
						left: 0,
						top: uni.getSystemInfoSync().statusBarHeight + 44, //放置在titleNView下方。如果还想在webview上方加个地址栏的什么的，可以继续降低TOP值
						width: wv_w,
						height: wv_h
					});
				}
			});
			_this.is_fullScreen = false;
			return true
		} else {
			wv.close();
		}
		// #endif
	},
	filters: {
		// 课程时间格式化
		course_time_filter(val, format) {
			if (!val) return '';
			return new Date(val * 1000).format(format || 'MM.dd');
		},
		// 获取课程类型
		course_type_filter(val) {
			return val == 2 ? '录播' : '直播';
		}
	},
	// #ifdef APP-PLUS
	watch:{
		index(val){
			if(_this.is_live_start){
				wv.close();
				_this.is_live_start = false
			}
		}
	},
	// #endif
	methods: {
		reload(index){
			_this.outlineList = uni.getStorageSync('outlineList');
			_this.navClick(+index || 0);
			_this.dataList = _this.outlineList.map(x => ({
				files_type: x.extend_source_type == '文档' ? 1 : x.extend_source_type == '视频' ? 2 : x.extend_source_type == '音频' ? 3: 0,
				name: x.detail_title,
				type: '课程资料',
				url: x.extend_source_url
			}));
			uni.hideLoading()
		},
		titleNav(index) {
			this.titleIndex = index;
		},
		// 载入web-view
		/**
		 * @param	config	直播的配置项
		 * @param	option	webview 的配置项，还不知道能不能生效
		 **/
		loadWebView(config, option) {
			console.log('_ start load web-view');
			var param = Object.keys(config)
				.map(x => x + '=' + encodeURIComponent(config[x]))
				.join('&');
			console.log(' _ get param with := ' + param);
			// #ifdef APP-PLUS
			console.log('webview option config ===> ', JSON.stringify(option));
			wv = plus.webview.create('', 'custom-webview', {
				plusrequire: 'none', //禁止远程网页使用plus的API，有些使用mui制作的网页可能会监听plus.key，造成关闭页面混乱，可以通过这种方式禁止
				'uni-app': 'none', //不加载uni-app渲染层框架，避免样式冲突
				top: uni.getSystemInfoSync().statusBarHeight + 44, //放置在titleNView下方。如果还想在webview上方加个地址栏的什么的，可以继续降低TOP值
				height: option.height,
				width: option.width
			});
			wv_h = option.height, wv_w = option.width
			wv.loadURL('/hybrid/html/screen.html?' + param);
			wv.addEventListener('UniAppJSBridgeReady', function(e) {
				console.log(' _ active WebView event listen ');
				console.log(' _ get message => ', e);
			});
			var currentWebview = this.$mp.page.$getAppWebview(); //获取当前页面的webview对象
			currentWebview.append(wv); //一定要append到当前的页面里！！！才能跟随当前页面一起做动画，一起关闭

			// #endif
		},
		webMessage(data) {
			console.log(data);
		},
		// 倒计时结束处理
		handleTimeCount(){
			// current outline
			var _t = _this.outlineList[_this.index]
			if(_t.begin == 2 && _t.course_service_type == 1){
				_this.outlineList[_this.index].begin = 1
				uni.setStorage({
					key: 'outlineList',
					data: _this.outlineList,
					success() {
						_this.reload(_this.index)					
					}
				})
				_this.$forceUpdate()
			}
		},
		download(url) {
			uni.showModal({
				title: '提示',
				content: '下载目标文件？',
				success: function(res) {
					if (res.confirm) {
						uni.downloadFile({
							url: url,
							success: res => {
								if (res.statusCode == 200) {
									uni.showToast({
										title: '下载成功',
										icon: 'none'
									});
									var path = res.tempFilePath;
									uni.openDocument({
										filePath: path,
										success: function(res) {
											console.log('打开文档成功');
										}
									});
								}
							},
							fail: res => {
								uni.showToast({
									title: '下载失败',
									icon: 'none'
								});
							}
						});
					}
				}
			});
		},
		// 获取声网令牌
		getToken() {
			return this.$zbapi.apiPost(`parent/agora/token/${this.course_id}`, { user_id: this.user_id }).then(res => {
				if (res.data.code == 0) {
					var val = res.data.data;
					this.rtcConfig.channel = val.channelName;
					this.rtcConfig.key = val.accessToken;
					this.rtcConfig.uid = val.uid;
				} else {
					throw Exception('[Server Error]:: get agora token with res : ', res);
				}
			});
		},
		// 尝试全屏
		fullScreen() {
			console.log(' _ set full Screen');
			// #ifdef APP-PLUS
			// 获取设备屏幕大小信息
			_this.is_fullScreen = true;
			uni.getSystemInfo({
				success(res) {
					console.log(' _ get System Info success := ', res);
					wv.setStyle({
						left: 0,
						top: uni.getSystemInfoSync().statusBarHeight + 44, //放置在titleNView下方。如果还想在webview上方加个地址栏的什么的，可以继续降低TOP值
						width: res.windowWidth + 4, // 好像有点不够，加上点凑数
						height: res.windowHeight + 2
					});
				}
			});
			// #endif
		},
		navClick(index, id) {
			this.index = index;
			this.saveId = id;
			if (this.outlineList[index].begin == 2) {
				this.outlineList[index].src = '';
				uni.showToast({
					title: '当前课程未开始~',
					icon: 'none'
				});
			} else if (this.outlineList[index].begin == 3) {
				this.outlineList[index].src = '';
				uni.showToast({
					title: '当前课程已经结束~',
					icon: 'none'
				});
			} else {
				this.outlineList[index].src = this.outlineList[index].src;
			}
		},
		// 点击开始直播
		startLive() {
			// 先请求 令牌
			_this
				.getToken()
				.catch(err => {
					uni.showToast({
						icon: 'none',
						title: '服务器异常，请稍后重试~'
					});
					// 获得令牌，则载入web-view
				})
				.then(a => {
					_this.rtcConfig.live = 1;
					_this.is_live_start = true;
					_this.loadWebView(_this.rtcConfig, { height: wv_h || 320, width: wv_w || 620 });
				});
		},
		// 点击测试播放
		testLive() {
			console.log('_ start test Live');
			// 先请求 令牌
			_this
				.getToken()
				.catch(err => {
					uni.showToast({
						icon: 'none',
						title: '服务器异常，请稍后重试~'
					});
					// 获得令牌，则载入web-view
				})
				.then(a => {
					_this.rtcConfig.live = 0;
					_this.is_live_start = true;		// 这边都要处理下，防止点击到别的
					_this.loadWebView(_this.rtcConfig, { height: wv_h || 320, width: wv_w || 620 });
				});
		}
	}
};
</script>

<style>
@import url('../../static/font_lesson/iconfont.css');
page {
	background: #f7f7f7;
}
.video-opration-bar {
	background-color: #fff;
	text-align: right;
	padding: 0 30upx;
}
.top {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	z-index: 1;
}
video {
	width: 100%;
	height: 422upx;
	display: flex;
	background-size: contain;
	background-color: #fefefe;
	position: relative;
	top: 0;
}
.live-box {
	width: 100%;
	height: 422upx;
	display: flex;
	background-size: contain;
	background-color: #fefefe;
	position: relative;
	top: 0;
	/* #ifdef H5 */
	margin-top: 88upx;
	/* #endif */
}
.live-box-warp {
	width: 100%;
	height: 422upx;
	display: flex;
	background: #999999;
	opacity: 0.7;
	position: absolute;
}
.start-live {
	width: 100upx;
	height: 100upx;
	z-index: 10;
	/* #ifdef H5 */
	height: auto;
	/* #endif */
	margin: auto;
	cursor: pointer;
}
.icon-shipin {
	font-size: 100upx;
	color: #fefefe;
}
.live-summary {
	padding-top: 70upx;
	margin: auto;
	text-align: center;
	z-index: 10;
}
.live-summary .live-tip {
	font-size: 36upx;
	font-family: Source Han Sans CN;
	font-weight: 400;
	line-height: 60upx;
	color: #fff;
}
.live-summary .live-time-count {
	font-size: 56upx;
	font-family: Source Han Sans CN;
	font-weight: 400;
	line-height: 100upx;
	color: #fff;
}
.live-summary .live-btn-bar {
}
.live-summary .live-btn-bar .live-btn {
	width: 160upx;
	height: 56upx;
	background: #999;
	border-radius: 36upx;
	display: inline-block;
	margin: 0 20upx;
}
.live-summary .live-btn-bar .live-btn text {
	font-size: 24upx;
	font-family: Source Han Sans CN;
	font-weight: 400;
	line-height: 40upx;
	color: #ffffff;
}
.info {
	padding: 30upx;
	width: calc(100% - 60upx);
	background: #ffffff;
	display: flex;
	justify-content: space-between;
	/* margin-top: -28upx; */
	border-bottom: 10upx solid #f7f7f7;
}
.info-right {
	color: #666666;
	font-size: 26upx;
}
.info-right i {
	font-size: 36upx;
}
.title {
	width: 100%;
	height: 90upx;
	background: #ffffff;
	display: flex;
	align-items: center;
}
.title-name {
	width: 50%;
	color: #666666;
	font-size: 32upx;
	line-height: 86upx;
	display: flex;
	align-items: center;
	flex-direction: column;
}
.title-item-active {
	color: #fe9900;
	font-size: 36upx;
	font-weight: bold;
}
.title-item-active:after {
	content: '';
	width: 200upx;
	height: 4upx;
	background: #fe9900;
}
/* 课程列表 */
.list {
	width: calc(100% - 60upx);
	margin: 0 30upx 100upx;
	background: #ffffff;
	border-radius: 20upx;
	position: absolute;
	top: 700upx;
}
.list-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20upx;
	border-top: 2upx solid #e5e5e5;
}
.list-item:first-child {
	border: none;
}
.list-item-info {
	width: 85%;
}
.list-item-index {
	color: #999999;
	display: flex;
	justify-content: flex-start;
	align-items: center;
}
.list-item-name {
	color: #333333;
	font-size: 34upx;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}
.list-item-icon {
	text-align: center;
	width: 104upx;
}
.list-item-icon view {
	color: #cccccc;
	font-size: 26upx;
	white-space: nowrap;
}
.list-item-icon i {
	color: #999999;
	font-size: 40upx;
}
.list-item-begin {
	color: #fe9900 !important;
	font-size: 26upx;
}
</style>
